<template>
  <Content title="返工执行详情">
    <view class="device-details" :style="data.id ? 'padding-bottom:150px' : ''">
      <template v-if="!data.id">
        <view class="no-data">
          <Empty text="无历史记录"></Empty>
        </view>
      </template>
      <view class="content" v-else>
        <view class="main-box">
          <u-form
            labelPosition="left"
            :model="model"
            labelWidth="85"
            labelAlign="left"
            :rules="rules"
            ref="uForm"
          >
            <view class="info-box">
              <view class="text-box">
                <text class="label">工单号:</text>
                <text class="value">{{ data.workOrder }}</text>
              </view>
              <view class="text-box">
                <text class="label">产品编号:</text>
                <text class="value">{{ data.productNumber }}</text>
              </view>
              <view class="text-box">
                <text class="label">设备编号:</text>
                <text class="value">{{ data.equipmentNumber }}</text>
              </view>
              <view class="text-box">
                <text class="label">产品名称:</text>
                <text class="value">{{ data.materialName }}</text>
              </view>
              <view class="text-box">
                <text class="label">发起人:</text>
                <text class="value">{{ data.initiator }}</text>
              </view>
              <view class="text-box">
                <text class="label">发起数量:</text>
                <text class="value">{{ data.remainingQuantity }}</text>
              </view>
              <view class="text-box">
                <text class="label">发起时间:</text>
                <text class="value">{{ data.reworkStartTime }}</text>
              </view>
              <view class="text-box">
                <text class="label">重量单位:</text>
                <text class="value">{{ data.weightUnit }}</text>
              </view>
            </view>

            <template v-if="data.reworkStatus == '处理中'">
              <view class="info-box">
                <view class="title">
                  <text class="txt">处理结果</text>
                </view>
                <view class="text-box" style="margin-bottom: 0">
                  <u-form-item
                    label=""
                    prop="processingType"
                    style="width: 100%"
                    ><!-- required -->
                    <u-radio-group
                      class="box-input"
                      v-model="model.processingType"
                    >
                      <u-radio
                        label="合格"
                        name="合格"
                        style="margin-right: 20px"
                      ></u-radio>
                      <u-radio
                        label="报废"
                        name="报废"
                        style="margin-right: 20px"
                      ></u-radio>
                    </u-radio-group>
                  </u-form-item>
                </view>

                <view
                  class="u-border-bottom"
                  style="margin-bottom: 10px"
                ></view>

                <view class="input-box">
                  <u-form-item label="班次时间:" prop="shiftTime" required>
                    <MyDate
                      @change="getShiftList"
                      v-model="model.shiftTime"
                      placeholder="请选择"
                    ></MyDate>
                  </u-form-item>
                </view>

                <view class="input-box">
                  <u-form-item label="班次:" prop="shift" required>
                    <uni-data-select
                      v-model="model.shift"
                      :localdata="shiftList"
                      placeholder="请选择"
                    ></uni-data-select>
                  </u-form-item>
                </view>

                <view class="input-box">
                  <u-form-item label="提报方式" prop="reportingMethod" required>
                    <uni-data-select
                      v-model="model.reportingMethod"
                      :localdata="wayList"
                      placeholder="请选择"
                    ></uni-data-select>
                  </u-form-item>
                </view>
                <view class="input-box">
                  <u-form-item
                    :label="
                      model.processingType === '合格'
                        ? model.reportingMethod == '重量'
                          ? '合格重量'
                          : '合格数量'
                        : model.reportingMethod == '重量'
                        ? '报废重量'
                        : '报废数量'
                    "
                    required
                    prop="reportedQuantity"
                  >
                    <u-input
                      class="box-input"
                      label
                      type="number"
                      v-model="model.reportedQuantity"
                      :readonly="model.processingType === '报废'"
                      placeholder="请输入"
                      clearable
                    ></u-input>
                  </u-form-item>
                </view>
                <view class="input-box" v-if="model.processingType === '合格'">
                  <u-form-item
                    label="入库仓库:"
                    prop="inWarehouseName"
                    required
                  >
                    <uni-data-select
                      v-model="model.inWarehouseName"
                      :localdata="wareHouses"
                      placeholder="请选择"
                    ></uni-data-select>
                  </u-form-item>
                </view>
              </view>

              <view class="info-box" v-if="model.processingType === '报废'">
                <view class="title">
                  <text class="txt"
                    ><i style="color: red; margin-right: 10px">*</i
                    >报废原因</text
                  >
                </view>
                <view class="text-box all-width" style="margin-bottom: 0">
                  <u-form-item label="" prop="outReason" style="width: 100%">
                    <u-radio-group class="box-input" v-model="model.outReason">
                      <u-radio
                        :label="item.value"
                        :name="item.value"
                        v-for="item in ngList"
                        :key="item.value"
                      ></u-radio>
                    </u-radio-group>
                  </u-form-item>
                </view>
              </view>

              <view class="info-box" v-if="model.processingType === '报废'">
                <view class="title">
                  <text class="txt">不良项(可搜选)</text>
                </view>
                <view
                  class="text-box"
                  v-for="(item, index) in efectiveList"
                  :key="item.ngCode"
                >
                  <text class="label">{{ item.ngCode }}:</text>
                  <view class="value">
                    <u-form-item label="" prop="ngNumber">
                      <u-input
                        label
                        v-model="item.ngNumber"
                        type="number"
                        @blur="keyUp($event, index, true)"
                        placeholder="请填写"
                        clearable
                      ></u-input>
                    </u-form-item>
                  </view>
                </view>
              </view>

              <view class="info-box">
                <view class="title">
                  <text class="txt">返工备注</text>
                </view>
                <view class="text-box" style="margin-bottom: 0">
                  <u-form-item label="" prop="remarks" style="width: 100%">
                    <u-textarea
                      v-model="model.remarks"
                      placeholder="请填写备注"
                    ></u-textarea>
                  </u-form-item>
                </view>
              </view>
            </template>
          </u-form>
        </view>
      </view>

      <view class="btn-v" v-if="data.id">
        <view class="but-box">
          <u-button
            class="btn"
            @click="start"
            v-if="data.reworkStatus == '未开始'"
            type="primary"
            text="返工开始"
          ></u-button>
          <u-button
            class="btn"
            type="primary"
            v-else
            @click="submit"
            text="返工完成"
          ></u-button>
        </view>
      </view>
    </view>
  </Content>
</template>

<script>
import Content from "@/components/content/index";
import fetch from "@/utils/fetch";
import Empty from "@/components/empty";
import MyDate from "@/components/myDate.vue";
import { getNotice, setNotice } from "@/store/user.js";
export default {
  components: {
    Content,
    MyDate,
    Empty,
  },
  data() {
    return {
      applicationNumber: "",
      data: {},
      model: {
        shift: "",
        applicationNumber: "",
        id: "",
        inboundWarehouse: "",
        processingType: "合格",
        remarks: "",
        outReason: "",
        reportedQuantity: null,
        reportingMethod: "按数量",
        shift: "",
        shiftTime: "",
        workOrder: "",
      },
      changingType: "",
      rules: {
        shift: {
          required: true,
          message: "请选择",
          trigger: ["blur", "change"],
        },
        shiftTime: {
          required: true,
          message: "请选择",
          trigger: ["blur", "change"],
        },
        reportingMethod: {
          required: true,
          message: "请选择",
          trigger: ["blur", "change"],
        },
        reportedQuantity: {
          required: true,
          type: "integer",
          message: "请输入正整数",
          trigger: ["blur", "change"],
        },
        outReason: {
          required: true,
          message: "请输入",
          trigger: ["blur", "change"],
        },
        inWarehouseName: {
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
      },
      navIndex: 0,
      type: "1",
      fileList: [],
      shiftList: [],
      ngList: [],
      efectiveList: [],
      inboundWarehouseList: [],
      wayList: [
        {
          text: "按数量",
          value: "按数量",
        },
        {
          text: "按重量",
          value: "按重量",
        },
      ],
      wareHouses: [],
    };
  },
  watch: {
    efectiveList: {
      deep: true,
      handler() {
        this.getAllNum();
      },
    },
  },
  onLoad: function (option) {
    //option为object类型，会序列化上个页面传递的参数
    this.applicationNumber = option.applicationNumber;
  },
  onReady: function () {
    console.log(this.model.shiftTime);
    this.getList().then(() => {
      this.getShiftList();
      this.getPoorList();
      this.getWareHouseList();
      this.getEfectiveListList();
    });
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    if (this.$refs.uForm) this.$refs.uForm.setRules(this.rules);
  },
  onShow: function () {},
  mounted() {},
  methods: {
    getList() {
      const that = this;
      return fetch("get", "/dms/mobileEnd/getReworkByWorkOrder", {
        applicationNumber: that.applicationNumber,
      }).then((res) => {
        let data = res.data || {};
        this.data = data;
        this.model = Object.assign(this.model, {
          applicationNumber: that.applicationNumber,
          id: data.id,
          inboundWarehouse: data.inboundWarehouse,
          processingType: data.processingType || "合格",
          remarks: data.remarks,
          reportedQuantity: data.reportedQuantity
            ? parseInt(data.reportedQuantity)
            : null,
          reportingMethod: data.reportingMethod || "按数量",
          shift: data.shift,
          shiftTime:
            data.shiftTime || this.$dayjs(new Date()).format("YYYY-MM-DD"),
          workOrder: data.workOrder,
        });
        this.getShiftList();
        this.efectiveList = data.ngList || [];
      });
    },
    getEfectiveListList() {
      const that = this;
      if (this.efectiveList.length > 0) return;
      this.efectiveList = [];
      fetch("get", "/dms/faultCategory/dictList", {
        name: "不良项",
      }).then((res) => {
        // that.$set(that.model,'changingType',null)
        for (let i = 0; i < res.data.length; i++) {
          that.efectiveList.push({
            ngNumber: 0,
            ngCode: res.data[i].value,
          });
        }
      });
    },
    getAllNum() {
      let res = 0;
      for (let i = 0; i < this.efectiveList.length; i++) {
        res = this.efectiveList[i].ngNumber - 0 + res;
      }
      this.model.reportedQuantity = res;
    },
    getPoorList() {
      const that = this;
      this.ngList = [];
      fetch("get", "/dms/faultCategory/dictList", {
        name: "报废",
      }).then((res) => {
        // that.$set(that.model,'changingType',null)
        that.ngList = res.data;
      });
    },
    //班次列表
    getShiftList() {
      const that = this;
      console.log("this.model", this.model, this.data);
      return fetch("get", "/dms/mobile/getShiftList", {
        deviceNo: this.data.equipmentNumber,
        shiftDate: this.model.shiftTime,
      }).then((res) => {
        const now = that.$dayjs().format("YYYY-MM-DD") + " ";
        const newDate = that.$dayjs().format("YYYY-MM-DD HH:mm:ss");
        const now1 = that.$dayjs().add(1, "day").format("YYYY-MM-DD") + " ";
        that.shiftList = res.data.map((item) => {
          const startTime = now + item.shiftStartTime;
          let endTime = now + item.shiftEndTime;
          if (endTime < startTime) {
            endTime = now1 + item.shiftEndTime;
          }
          console.log("startTime, endTime", startTime, endTime, newDate);
          if (newDate > startTime && newDate < endTime) {
            that.model.shift = item.shift;
            that.model.shiftId = item.id;
          }
          return {
            ...item,
            value: item.shift,
            text: item.shift,
          };
        });
        if (!that.model.shift) {
          that.model.shift = that.shiftList[0].shift;
          that.model.shiftId = that.shiftList[0].id;
        }

        console.log("that.shiftList", that.shiftList);
      });
    },
    getWareHouseList() {
      fetch("get", "/dms/mobileEnd/getQualifiedWarehouse", {
        deviceNo: this.data.equipmentNumber,
      }).then((res) => {
        this.wareHouses = [res.data].map((item) => ({
          value: item.backupName,
          text: item.backupName,
        }));
        this.model.inWarehouseName = res.data.backupName;
        this.model.warehouseId = res.data.id;
      });
    },
    keyUp(e, index, money) {
      if (!this.efectiveList[index].ngNumber) {
        return (this.efectiveList[index].ngNumber = 0);
      }
      let num = "";
      if (money) {
        num = this.efectiveList[index].ngNumber.match(/^\d*(\.?\d{0,2})/g)[0];
      } else {
        num = this.efectiveList[index].ngNumber
          .replace(/^[^\d]+$/g, "")
          .split(".")[0];
      }
      this.$set(this.efectiveList[index], "ngNumber", num - 0);
    },
    toPath() {
      uni.navigateTo({
        url:
          "/pages/staging/handling-defective-products/reporting-records?workOrder=" +
          this.id,
        animationType: "pop-in",
      });
    },
    start() {
      const that = this;
      that.$loading.open();
      fetch("post", "/dms/mobileEnd/addRework", null, {
        applicationNumber: this.applicationNumber,
      }).then((data) => {
        that.$loading.close();
        uni.$emit("openToast", {
          type: "success",
          title: "返工开始成功",
          complete() {
            that.getList();
          },
        });
      });
    },
    submit() {
      const that = this;
      let data = {
        ...that.model,
        ngList: that.efectiveList,
      };
      if (that.model.processingType === "合格") {
        delete data.ngList;
        delete data.outReason;
      } else {
        delete data.reportedQuantity;
      }
      that.$refs.uForm.validate().then((valid) => {
        if (valid) {
          that.$loading.open();
          fetch("post", "/dms/mobileEnd/reworkOperation", data).then((data) => {
            that.$loading.close();
            uni.$emit("openToast", {
              type: "success",
              title: "返工完成成功",
              complete() {
                uni.navigateBack({
                  delta: 1,
                });
              },
            });
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.device-details {
  height: 100%;
  overflow: auto;

  .content {
    min-height: 100%;
  }

  .title {
    font-size: 32rpx;
    margin-bottom: 20rpx;
    padding: 0 40rpx 20rpx 40rpx;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;

    .txt {
      flex: 1;
    }

    .tag-box {
      display: flex;
      align-items: center;
    }
  }

  .content-top {
    padding: 40rpx;

    .state {
      color: #f17a0a;
      margin-bottom: 20rpx;
    }
  }

  .info-box .text-box .label {
    width: 85px;
  }
  .search-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 60rpx;

    .label {
      margin: 0 20rpx;
    }
  }
}
</style>
